const dbApi = require('../models/db')
const handTime = require('../middleware/handtimestamp')

// 频道文章列表
exports.artChannelsList = async (req, res, next) => {
  let { channelId, page = 1 } = req.query
  const onpage = page > 1 ? (page - 1) * 10 : 0
  const sql = `SELECT a.id,a.title,a.content,a.username,a.commentcount,a.time,a.cover,b.division 
  FROM articles a  INNER JOIN channel b ON a.channel_id = b.id 
  WHERE b.id = ${channelId} ORDER BY a.time DESC LIMIT  ${onpage},10`
  try {
    const data = await dbApi.query(sql)
    await handTime(data)
    page++
    res.status(200).json({
      data,
      page,
      message: 'succsed'
    })
  } catch (error) {
    next(error)
  }
}

// 所有频道列表
exports.ChannelsList = async (req, res, next) => {
  const sql = 'SELECT * FROM channel'
  try {
    // 处理请求
    const channels = await dbApi.query(sql)
    res.status(200).json({
      channels,
      message: 'succeed'
    })
  } catch (error) {
    next(error)
  }
}

// 添加用户频道
exports.addChannel = async (req, res, next) => {
  const { channelId } = req.body
  const sql = `INSERT INTO userchannle (username,channel_id)
  VALUES ('${req.user.username}',${channelId}) `
  try {
    // 处理请求
    const { affectedRows: data } = await dbApi.query(sql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}

// 删除用户频道
exports.delChannel = async (req, res, next) => {
  const { channelId } = req.params
  const sql = `DELETE FROM userchannle WHERE
   username = '${req.user.username}' AND channel_id = ${channelId} `
  try {
    // 处理请求
    const { affectedRows: data } = await dbApi.query(sql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}
